<template>
  <div class="root">
    <el-card>
      <!-- 头部 -->
      <el-header>
        <el-row type="flex">
          <el-col>
            <el-button
              type="primary"
              @click="isShowDialog = true"
            >新增</el-button>
          </el-col>
          <el-col :span="10">
            <el-select
              v-model="getListConfig.agent_contains"
              :clearable="true"
              placeholder="请选择"
            >
              <el-option
                v-for="item in agentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col>
            <el-input
              v-model="getListConfig.name_contains"
              placeholder="请输入内容"
              class="input-with-select"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="searchFn"
              />
            </el-input>
          </el-col>
        </el-row>
      </el-header>
      <!-- 表格 -->
      <transition name="fade-transform" mode="out-in">
        <el-table v-show="isshow" :data="clientList" border="">
          <el-table-column label="封面">
            <template v-slot="{ row }">
              <img :src="row.image" alt="" height="100px">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="邮箱" prop="email" />
          <el-table-column label="电话" prop="phone" />
          <el-table-column label="经纪" prop="agent.name" />
          <el-table-column label="微信" prop="wechat" />
          <el-table-column label="介绍" prop="desc" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button type="primary" @click="edtFn(row.id)">编辑</el-button>
              <el-button type="danger" @click="delFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </transition>
      <!-- 模态框 -->
      <el-dialog
        :visible="isShowDialog"
        title="客户管理"
        center
        @close="btnCan"
      >
        <el-form
          ref="dialogForm"
          :model="formData"
          :rules="rules"
          label-width="80px"
        >
          <!-- 下拉框 -->
          <el-form-item label="经纪" prop="agent">
            <el-select v-model="formData.agent">
              <el-option
                v-for="item in agentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- 输入框 -->
          <el-form-item label="名字" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="formData.phone" />
          </el-form-item>
          <el-form-item label="微信" prop="wechat">
            <el-input v-model="formData.wechat" />
          </el-form-item>
          <!-- 文本框 -->
          <el-form-item label="描述" prop="desc">
            <el-input v-model="formData.desc" type="textarea" />
          </el-form-item>
          <!-- 上传组件 单个 -->
          <el-form-item label="封面">
            <ImageUpload ref="imageUploadCom" :is-limit="true" />
          </el-form-item>
        </el-form>
        <!-- 按钮 -->
        <template v-slot:footer>
          <el-button @click="btnCan">取消</el-button>
          <el-button type="primary" @click="btnCfm">确定</el-button>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        hide-on-single-page
        layout="prev, pager, next"
        :total="total"
        :page-size="getListConfig._limit"
        :current-page="currentPage"
        @current-change="currentChange"
      />
    </el-card>
  </div>
</template>

<script>
// 引入客户相关接口
import { addClient, delClient, edtClinet, getClientCount, getClientList, getClinetDetailById } from '@/api/customer'
// 引入经纪接口
import { getAgentList } from '@/api/agent'
// 引入组件
import ImageUpload from '../building/component/imageUpload.vue'
export default {
  components: {
    ImageUpload
  },
  data() {
    return {
      isshow: true, // 切图效果
      agentList: [], // 经纪列表
      clientList: [], // 客户列表
      isShowDialog: false, // 控制弹出框的展示
      formData: {
        name: '',
        desc: '',
        image: '',
        agent: '',
        email: '',
        phone: '',
        wechat: '', // 区分新增和编辑
        id: ''
      }, // 请求参数
      // 校验规则
      rules: {
        agent: [{ required: true, message: '经纪不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名字不能为空', trigger: 'blur' }]
      },
      getListConfig: {
        _limit: 2, // 限制条数
        _start: 0, // 从默认排序的第几个结果开始
        name_contains: '', // 搜索 标题
        agent_contains: '' // 搜索 中介
      }, // 搜索条件配置
      total: 0, // 总条数
      currentPage: 1
    }
  },
  created() {
    // 客户列表
    this.getClientList()
    // 中介列表
    this.getAgentList()
  },
  methods: {
    // 封装初始化客户列表接口
    async getClientList() {
      // 获取房产列表
      const { data } = await getClientList(this.getListConfig)
      // 获取房产总数
      const res = await getClientCount(this.getListConfig)
      this.clientList = data // 房产列表
      this.total = res.data // 总条数
    },
    // 封装获取中介列表
    async getAgentList() {
      const { data } = await getAgentList()
      console.log('中介', data)
      // 保存到全局
      this.agentList = data
    },
    // 编辑按钮事件
    async edtFn(val) {
      // 调接口
      const { data } = await getClinetDetailById(val)
      console.log('140', data.agent)
      // 数据的回显
      this.formData = data
      // // 数据结构bug的处理,formData.agent需要字符串,接口返回对象
      this.formData.agent = data.agent ? data.agent.id : ''
      // 把插槽的id保存到全局
      this.formData.id = val
      // 弹出模态框
      this.isShowDialog = true
      // 补全图片回显地址
      this.$nextTick(() => {
        // 封面回显
        this.$refs.imageUploadCom.fileList = [{ url: this.formData.image }]
      })
    },
    // 删除按钮事件
    async delFn(val) {
      // 二次确认
      await this.$confirm('确认删除?')
      // 调用删除接口
      await delClient(val)
      // 提示用户
      this.$message.success('删除成功')
      // 定义总页数
      const totalPage = Math.ceil(this.total / this.getListConfig._limit)
      // 判断是否是最后一页的最后一项,且不是第一页
      if (this.currentPage === totalPage && this.total % this.getListConfig._limit === 1 && this.currentPage > 1) {
        // 页数自减
        this.currentPage--
        // 重置起始页面
        this.getListConfig._start = this.getListConfig._limit * (this.currentPage - 1)
      }
      // 刷新
      this.getClientList()
    },
    // 模态框取消
    async btnCan() {
      // 清空校验
      await this.$refs.dialogForm.resetFields()
      // 重置表单
      this.formData = {
        name: '',
        desc: '',
        image: '',
        agent: '',
        email: '',
        phone: '',
        wechat: '', // 区分新增和编辑
        id: ''
      }
      // 清空上传图片的数据
      this.$refs.imageUploadCom.fileList = []
      // 关闭模态框
      this.isShowDialog = false
    },
    // 模态框确定
    async btnCfm() {
      // 封面相关操作
      const fileList = this.$refs.imageUploadCom.fileList
      // 判断封面是否上传成功
      if (fileList[0] && fileList[0].status !== 'success') {
        // 提示用户
        this.$message.warning('请等待封面上传成功')
        // 退出
        return
      }
      // 将封面添加到formData表单
      this.formData.image = fileList[0] ? fileList[0].url : ''

      // 校验表单
      await this.$refs.dialogForm.validate()
      // 判断有无id,没有是新增,有是编辑
      if (this.formData.id) {
        // 调用编辑接口
        const res = await edtClinet(this.formData)
        console.log('编辑', res)
      } else {
        // 调用新增接口
        const res = await addClient(this.formData)
        console.log('新增', res)
        if (this.total % this.getListConfig._limit === 0) {
        // 总数除以每页显示数，取余为0，说明是最后一项,新页面整除后 +1
          const newPage = this.total / this.getListConfig._limit + 1
          // 0->0 1->2 2->4
          this.getListConfig._start = (newPage - 1) * this.getListConfig._limit
          // console.log('最后一项', this.getListConfig._start)
        } else {
        // 不是最后一项，则除后取天花板数
          const newPage = Math.ceil(this.total / this.getListConfig._limit)
          this.getListConfig._start = (newPage - 1) * this.getListConfig._limit
          // console.log('不是最后一项', this.getListConfig._start)
        }
      }
      // 提示用户
      this.$message.success('操作成功')
      // 重置表单
      // 重置表单
      this.formData = {
        name: '',
        desc: '',
        image: '',
        agent: '',
        email: '',
        phone: '',
        wechat: '', // 区分新增和编辑
        id: ''
      }
      // 关闭模态框
      this.isShowDialog = false
      // 重新渲染
      await this.getClientList()
      // 重新给页面赋值
      this.currentPage = Math.ceil(this.total / this.getListConfig._limit)
    },
    // 点击搜索按钮
    async searchFn() {
      // 结果从头开始
      this.getListConfig._start = ''
      // 重置页头
      this.currentPage = 1
      // 带搜索条件的地产列表
      this.getClientList()
    },
    // 点击分页
    currentChange(currentPage) {
      this.isshow = false
      setTimeout(() => {
        this.isshow = true
      }, 100)
      // 保存到全局
      this.currentPage = currentPage
      // 重置起始页面
      this.getListConfig._start = this.getListConfig._limit * (currentPage - 1)
      // 调用获取房产列表渲染接口
      this.getClientList()
    }
  }
}
</script>

<style lang="scss" scoped>
.fade-transform-leave-active,
.fade-transform-enter-active {
  transition: all 0.1s;
}
.fade-transform-enter {
  opacity: 0;
  transform: translateX(-80px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(50px);
}
.root{
  margin-top: 20px;
  margin-left: 20px;
}
</style>
